package org.xs.ibatis.session;

import java.sql.Connection;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.dao.support.DaoSupport;
import org.springframework.transaction.support.TransactionSynchronizationManager;

 
public class Ibatis3DaoSupport extends DaoSupport {
	
    private SqlSessionFactory sessionFactory;
    private DataSource dataSource;

    public SqlSession openSession() {   
        SqlSession session = (SqlSession) TransactionSynchronizationManager
                .getResource(sessionFactory);

        if (session == null) {
            session = createSpringSqlSession();
        }

        return session;
    }

    public SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SqlSessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    
    public Object execute(SqlSessionCallback callback) {
        SqlSession session = openSession();

        try {
            return callback.doInSqlSession(session);
        }
        finally {
            session.close();
            SpringSqlSession springSession = (SpringSqlSession) session;

            if (!springSession.isRunningInTransaction()) {
                java.sql.Connection con = springSession.getConnection();

                if (con != null) {
                    try {
                        con.close();
                    }
                    catch (java.sql.SQLException sqle) {
                        
                    }
                }
                
            }
        }
    }

    @Override
    protected void checkDaoConfig() throws IllegalArgumentException {
        if (sessionFactory == null) {
            throw new IllegalArgumentException(
                    "Property 'sessionFactory' is required");
        }

        if (dataSource == null) {
            throw new IllegalArgumentException(
                    "Property 'dataSource' is required");
        }
    }
    //the session can't support transcation
    private SqlSession createSpringSqlSession() {
    	SqlSession sqlsession = null;
        try { 
        	if(sqlsession  == null){
        		Connection con = dataSource.getConnection();
            	sqlsession  = new SpringSqlSession(sessionFactory, dataSource,con,false);
            
        }
        	}
        catch (java.sql.SQLException sqle) {
            throw new org.springframework.jdbc.CannotGetJdbcConnectionException(
                    "Could not get JDBC Connection", sqle);
        } 
       
        return sqlsession;
    }
}
